<template>
  <el-dialog title="委外收货新增" :close-on-click-modal="false" :visible.sync="visible" center fullscreen>
    <el-button class="miui-dialog-close-btn" @click="visible = false">关闭页面</el-button>
    <el-form :model="dataForm" inline :rules="dataRule" ref="dataForm" label-width="80px">
      <el-row :gutter="15">
        <el-col :span="8">
          <el-form-item label="配镜单号">
            <el-input v-model="dataForm.saleBillId" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收入仓位" prop="inStockId">
            <el-select v-model="dataForm.inStockId" placeholder="请选择">
              <el-option v-for="item in stockOptions" :key="item.value" :label="item.name" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="订单单号">
            <el-input v-model="dataForm.billId" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="制造商">
            <el-input v-model="dataForm.supplyName" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="顾客姓名">
            <el-input v-model="dataForm.customerName" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="顾客电话">
            <el-input v-model="dataForm.customerPhone" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="运单单号">
            <el-input v-model="dataForm.transportBillId" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="订单类型">
            {{getSaleType(dataForm.consignType)}}
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="取镜日期">
            <el-input v-model="dataForm.takeMirroTime" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="销售门店" prop="deptId">
            <el-select v-model="dataForm.deptId" placeholder="请选择" disabled>
              <el-option v-for="item in deptOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" class="miui-textarea" style="width: 100%;">
            <el-input type="textarea" style="width: 100%;" v-model="dataForm.memo"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <table class="miui-table">
      <tr>
        <th>右眼(R)/左眼(L)</th>
        <th>球镜</th>
        <th>柱镜</th>
        <th>轴向</th>
        <th>基底</th>
        <th>曲率</th>
        <th>直径</th>
      </tr>
      <tr>
        <td>R</td>
        <td>{{optometry.ballGlassOd}}</td>
        <td>{{optometry.postGlassOd}}</td>
        <td>{{optometry.axesOd}}</td>
        <td>{{getBasalTypeData(optometry.basisOd)}}</td>
        <td>{{optometry.curvatureOd}}</td>
        <td>{{optometry.diameterOd}}</td>
      </tr>
      <tr>
        <td>L</td>
        <td>{{optometry.ballGlassOs}}</td>
        <td>{{optometry.postGlassOs}}</td>
        <td>{{optometry.axesOs}}</td>
        <td>{{getBasalTypeData(optometry.basisOs)}}</td>
        <td>{{optometry.curvatureOs}}</td>
        <td>{{optometry.diameterOs}}</td>
      </tr>
    </table>
    <el-table :data="dataList" border v-loading="dataListLoading" header-cell-class-name="miui-header-cell-style"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column prop="saleBillId" label="配镜单号" width="150"></el-table-column>
      <el-table-column prop="goodsName" label="商品名称"></el-table-column>
      <el-table-column prop="goodsSpec" label="商品型号" width="80"></el-table-column>
      <el-table-column prop="goodsQuantity" label="商品数量" width="80"></el-table-column>
      <el-table-column prop="glassFlag" label="镜片类型" width="80"></el-table-column>
      <el-table-column prop="batch" label="批次" width="150" v-if="dataForm.consignType == 1">
        <template slot-scope="scope">
          <el-form :model="scope.row" :rule="listRule">
            <el-form-item prop="batch">
              <el-input v-show="true" v-model="scope.row.batch"></el-input>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column prop="productionDate" label="生产日期" width="210" v-if="dataForm.consignType == 1">
        <template slot-scope="scope">
          <el-input v-model="scope.row.productionDate"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="invalidStr" label="有效期" width="160" v-if="dataForm.consignType == 1">
        <template slot-scope="scope">
          <el-input v-model="scope.row.invalidStr" style="width: 120px;" @change="invalidTimeChange(scope.row,scope.$index)"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="registerNum" label="注册证号" width="210" v-if="dataForm.consignType == 1">
        <template slot-scope="scope">
          <el-input v-model="scope.row.registerNum"></el-input>
        </template>
      </el-table-column>

    </el-table>

    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="dataFormSubmit" :loading="ischeck" v-prevent-re-click>保 存</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import { getUnConsignReceiptById, addConsignReceiptObj } from '@/api/eims/consign/consignReceipt.js'
  import { remote } from '@/api/admin/dict'
  import { checkDate } from '@/util/tools'
  import { getNowTime } from '@/api/eims/sale'
  import { getStockList } from '@/api/eims/stock.js'
  import { getDeptInfoByDeptType } from '@/api/admin/dept.js'

  import { mapGetters } from 'vuex'

  export default {
    data() {
      const validateNameInput = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('此项必填！'))
        } else {
          callback()
        }
      }
      return {
        ischeck: false,
        visible: false,
        dataForm: {
          id: 0,
          memo: '',
          inStockId: '',
          detailList: []
        },
        deptOptions: [],
        stockOptions: [],
        saleTypeData: [],
        dataList: [],
        optometry: {},
        dataListLoading: false,
        dataRule: {
          inStockId: [{
            required: true,
            message: '请选择入库仓位'
          }]
        },
        listRule: {
          batch: [{
              required: true,
              message: '请选择批次',
              trigger: 'blur'
            },
            {
              validator: validateNameInput,
              trigger: 'blur'
            }
          ]
        },
        selectionList: [],
        receiveListVisible: false
      }
    },
    computed: {
      ...mapGetters(['permissions', 'bizData', 'userInfo'])
    },
    methods: {
      // 获取当前时间
      async getNowDateStr(){
        let nowDateStr = ''
        await getNowTime().then(result => {
          nowDateStr = result.data.data
        })
        return nowDateStr
      },
      init(id) {
        this.getInStockList()
        this.getDeptList()
        this.dataForm.id = id || 0
        remote('sale_type').then(result => {
          this.saleTypeData = result.data.data
        })
        this.visible = true
        this.dataList = []
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            getUnConsignReceiptById(this.dataForm.id).then(response => {
              if(response.data.code == '0'){
                this.dataForm = response.data.data
                this.optometry = response.data.data.optometry
                let goodsData = response.data.data.detailList
                this.dataList = goodsData
                this.$set(this.dataForm,'inStockId',1)
              }else{
                this.$message.error(response.data.msg)
              }
            })
          }
        })
      },
      consignMethodChange(val) {
        this.dataList = [...this.dataList]
      },
      //  效期改变事件
      invalidTimeChange(data,index){
        this.getNowDateStr().then(result => {
          let reg = /^((?:19|20|21|22)\d\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$/
          let reg2 = /^((?:19|20|21|22)\d\d)-(0[1-9]|1[012])$/
          if(checkDate(data.invalidStr) && reg.test(data.invalidStr)){
            if(new Date(data.invalidStr).getTime() <= new Date(result).getTime()){
              data.invalidStr = ''
              this.$message.warning('效期不可小于当前日期')
            }
          }else if(reg2.test(data.invalidStr)){
            let nowMonth = result.substring(0,7)
            if(new Date(data.invalidStr).getTime() <= new Date(nowMonth).getTime()){
              data.invalidStr = ''
              this.$message.warning('效期不可小于当前日期')
            }
          }else{
            data.invalidStr = ''
            this.$message.error('请填写正确日期格式 2020-01-01 或 2020-01')
            return false
          }
        })

      },
      //获取配镜类型枚举
      getSaleType(value) {
        let obj = {};
        obj = this.saleTypeData.find((item) => {
          return item.value == value;
        });
        if (obj && obj.label) {
          return obj.label;
        }
      },
      //获取基地类型枚举
      getBasalTypeData(value) {
        let obj = {};
        obj = this.bizData.basalTypeData.find((item) => {
          return item.value === value;
        });
        if (obj && obj.label) {
          return obj.label;
        }
      },
      // 打开商品列表弹窗
      openReceiveListDialog() {
        this.receiveListVisible = true
        this.$nextTick(() => {
          this.$refs.receiveList.init()
        })
      },
      handleSelectionChange(val) {
        this.selectionList = val
      },
      // 删除选中的商品
      delTableData() {
        this.selectionList.forEach((item, index) => {
          for (let i = 0; i < this.dataList.length; i++) {
            if (this.dataList[i] == item) {
              this.dataList.splice(i, 1)
            }
          }
          this.selectionList = []
        })
      },
      //更新表单数据
      updateFormData(obj) {
        let _this = this
        this.dataList = obj
        obj.forEach(item => {
          this.dataForm.detailList.push({
            goodsId: item.goodsId
          })
        })
      },
      // 表单提交
      dataFormSubmit() {
        if (this.dataForm.consignType == "1") {
          for (let i = 0; i < this.dataList.length; i++) {
            if (!this.dataList[i].batch) {
              this.$message.warning("请输入批次")
              return
            }
            if (!this.dataList[i].invalidStr) {
              this.$message.warning("请输入效期")
              return
            }
          }
        }
        this.ischeck = true
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.dataForm.detailList.forEach((item, index) => {
              item.goodsQuantity = this.dataList[index].goodsQuantity,
                item.batch = this.dataList[index].batch,
                item.invalidTime = this.dataList[index].invalidTime,
                item.registerNum = this.dataList[index].registerNum
            })
            addConsignReceiptObj(this.dataForm).then(response => {
              if (response.data.code == 1) {
                this.$message.error(response.data.msg)
              } else {
                this.$message.success('订单收货成功')
                this.visible = false
                this.$emit('refreshDataList')
              }
              this.ischeck = false
            }).catch(() => {
              this.ischeck = false
            })
          }else{
            this.ischeck = false
          }
        })
      },
      getInStockList() {
        getStockList().then(response => {
          if(response.data.code == '0'){
            let dataList = response.data.data
            let options = []
            dataList.forEach(item => {
              options.push({
                value: item.id,
                name: item.name
              })
            })
            this.stockOptions = options
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      /*
       * *  获取所需数据字典
       */
      //  getDeptList(){
      //    fetchTree().then(result => {
      //      let dataList = result.data.data
      //      let options = []
      //      dataList.forEach(item => {
      //        options.push({value:item.id,name:item.name})
      //      })
      //      this.deptOptions = options
      //    })
      //  },
      //获取销售部门列表
      getDeptList() {
        getDeptInfoByDeptType(1).then(response => {
          if(response.data.code ==  '0'){
            this.deptOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
    }
  }
</script>

<style lang="scss" scoped="scoped">
  .miui-table {
    width: 100%;
    margin: 10px 0;

    tr th,
    tr td {
      background-color: #f4f5f7;
    }

    tr th,
    tr td {
      padding: 10px 8px;
      border: solid 1px #e7e7e7;
      text-align: center;
    }
  }
</style>
